import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()
    const { status, updatedBy, comment } = body

    if (!status || !updatedBy) {
      return NextResponse.json(
        { error: 'Status and updatedBy are required' },
        { status: 400 }
      )
    }

    const existingProduct = await db.product.findUnique({
      where: { id }
    })

    if (!existingProduct) {
      return NextResponse.json(
        { error: 'Product not found' },
        { status: 404 }
      )
    }

    // 检查用户是否存在，如果不存在则创建
    let user = await db.user.findUnique({
      where: { email: updatedBy }
    })

    if (!user) {
      user = await db.user.create({
        data: {
          email: updatedBy,
          name: updatedBy.split('@')[0]
        }
      })
    }

    // 检查状态转换是否有效
    const validTransitions = {
      'DRAFT': ['REVIEW', 'ARCHIVED'],
      'REVIEW': ['APPROVED', 'DRAFT', 'ARCHIVED'],
      'APPROVED': ['RELEASED', 'DRAFT', 'ARCHIVED'],
      'RELEASED': ['ARCHIVED'],
      'ARCHIVED': ['DRAFT']
    }

    const allowedTransitions = validTransitions[existingProduct.status as keyof typeof validTransitions] || []
    
    if (!allowedTransitions.includes(status)) {
      return NextResponse.json(
        { error: `Invalid status transition from ${existingProduct.status} to ${status}` },
        { status: 400 }
      )
    }

    const updatedProduct = await db.product.update({
      where: { id },
      data: {
        status,
        updatedAt: new Date()
      },
      include: {
        creator: {
          select: { id: true, name: true, email: true }
        }
      }
    })

    // 创建产品历史记录
    await db.productHistory.create({
      data: {
        productId: id,
        action: 'STATUS_CHANGED',
        fromState: existingProduct.status,
        toState: status,
        description: comment || `状态从 ${existingProduct.status} 变更为 ${status}`,
        userId: user.id
      }
    })

    return NextResponse.json(updatedProduct)
  } catch (error) {
    console.error('Error updating product status:', error)
    return NextResponse.json(
      { error: 'Failed to update product status' },
      { status: 500 }
    )
  }
}